<?php

namespace App\Http\Controllers\Api\Oauth\Oauth2;

use App\Core\Utils\TwHelper\Environment;
use App\Http\Controllers\Api\Controller as BaseController;
use Illuminate\Http\Request;
use App\Models\Oauth\UserModel;
use App\Models\Club\MemberModel;
use App\Services\Oauth\LoginService;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cookie;
use App\Models\Oauth\CodeModel;
use App\Models\Oauth\AuthorizeModel;
use App\Services\Oauth\Oauth2\Oauthor;
use App\Services\Oauth\Oauth2\AccessToken;
use App\Services\Oauth\User;
use App\Http\Resources\Base\UserResource;
use App\Exceptions\Response\Service\ServiceCode;
use App\Exceptions\Response\Service\ServiceException;
use App\Services\Oauth\Oauth2\App;
use App\Services\Oauth\RegistService;
use App\Services\Oauth\UserService;
use App\Core\Utils\TwHelper\CommFunction;
use App\Models\Oauth\DistrictModel;
use App\Services\Oauth\OauthorService;
use App\Services\Utils\TencentYun\ImageService;
use TencentYun\Image\ImageV2;



/**
 * 用户登录和注册等相关api
 */
class ApiOauthController extends BaseController
{
    /**
     * 客户端向认证服务器申请令牌的HTTP请求,
     * 接受请求，验证参数，并发放令牌
     */
    public function getAccessToken(Request $request)
    {
        //获取请求令牌（access_token）的参数，并做验证,
        //参数有(app_key、app_secret、grant_type、redirect_uri、code) 5个
        $appkey = $request->query('app_key', 'e89466d3d3f0eb2715d8a4ca');
        $app_secret = $request->query('app_secret', '235HJaeQ60kJ8mJ7DB50bsXVKJXx1CKl');
        $grant_type = $request->query('grant_type', 'authorization_code');
        $redirect_uri = $request->query('redirect_uri', 'http://txh.tongwei.cn');
        $code = $request->query('code', '');
        $oauth = new Oauthor($appkey);
        //验证请求的参数
        $oauth->checkParams($app_secret, $grant_type, $redirect_uri, $code);
        //验证授权码（code）的有效性
        $oauth->checkCode();
        //发放令牌（access_token）
        $data = $oauth->createAuthorize();
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 通过令牌，获取用户的信息
     */
    public function getUser(Request $request)
    {
        $this->validate($request, [
            'app_key' => 'required',
            'access_token' => 'required'
        ]);
        $appkey = $request->query('app_key', '');
        $access_token = $request->query('access_token', '');
        //验证app_key
        App::checkApp($appkey);
        $token = new AccessToken();
        //验证access_token,验证通过后并查询用户信息
        if ($token->checkAccessToken($access_token)) {
            $uid = $token->getUserId();
            $user = UserModel::getUserById($uid);
            if ($user) {
                unset($user['password']);
                $user = UserResource::makeAvatarDecode($user);
            } else {
                throw new ServiceException(ServiceCode::SERVICE_OAUTH_USER_NOT_EXIST, '', []);
            }
        }
        return $this->response->setResponseData($user)->getResponse();
    }

    /**
     * 刷新access_token，就是颁发新的access_token
     * refresh_token
     */
    public function refreshAccessToken(Request $request)
    {
        $this->validate($request, [
            'granttype' => 'required',
            'refresh_token' => 'required',
            'scope' => 'required',
        ]);
        $grantType = $request->query('granttype', '');
        $refreshToken = $request->query('refresh_token', '');
        $scope = $request->query('scope', 'basic');
        //验证refreshToken
        $data = AccessToken::checkRefreshToken($refreshToken, $scope, $grantType);
        if ($data) {
            $result = AccessToken::makeAuthorize($scope, $data['user_id']);
            return $this->response->setResponseData($result)->getResponse();
        }
    }

}